package com.android.physics;

import java.util.ArrayList;
import java.util.List;

import android.os.Handler;
import android.os.Message;

public class Time
{
    private final static int MSG_TICK = 1;
    private long mInterval;
    private Handler mHandler;
    
    private List<OnTimeListener> mOnTimeListeners = new ArrayList<OnTimeListener>();

    private long mCurrentTick = 0;
    private boolean mIsStarted = true;
    public Time()
    {
        this(0);
    }
    
    /**
     * @param interval Millisecond
     */
    public Time(long interval)
    {
        mInterval = interval;
        mHandler = new Handler()
        {
            public void handleMessage(Message msg) 
            {
                if (msg.what == MSG_TICK && mIsStarted)
                {
                    mCurrentTick++;
                    long timestamp = System.currentTimeMillis();
                    notifyTick();
                    long cost = System.currentTimeMillis() - timestamp;
                    mHandler.sendEmptyMessageDelayed(MSG_TICK, 
                            mInterval - cost > 0 ? mInterval - cost : 0);
                }
            };
        };
        mIsStarted = false;
    }
    
    public void release()
    {
        stop();
    }
    
    /**
     * @param interval Millisecond
     */
    public void setInterval(int interval)
    {
        mInterval = interval;
    }
    
    public long getCurrentTick()
    {
        return mCurrentTick;
    }
    
    public void start()
    {
        if (mIsStarted)
            return;
        
        mIsStarted = true;
        mHandler.removeMessages(MSG_TICK);
        mHandler.sendEmptyMessage(MSG_TICK);
    }
    
    public void stop()
    {
        if (!mIsStarted)
            return;
        mIsStarted = false;
        mHandler.removeMessages(MSG_TICK);
    }
    
    public void reset()
    {
        stop();
        mCurrentTick = 0;
    }
    
    public boolean isStarted()
    {
        return mIsStarted;
    }
    
    public interface OnTimeListener
    {
        void onTick();
    }
    
    public void regOnTimeListener(OnTimeListener listener)
    {
        if (listener == null)
        {
            throw new IllegalArgumentException("Input value is null");
        }
        mOnTimeListeners.add(listener);
    }
    
    public void unregOnTimeListener(OnTimeListener listener)
    {
        mOnTimeListeners.remove(listener);
    }
    
    private void notifyTick()
    {
        for (OnTimeListener listener : mOnTimeListeners)
        {
            listener.onTick();
        }
    }
}
